package service

import (
	"bytes"
	"context"
	"engine/dto"
	emodel "engine/model"
	"fmt"
	"github.com/elastic/go-elasticsearch/v8/esapi"
	"github.com/goccy/go-json"
	"github.com/shopspring/decimal"
	"io"
	"io/ioutil"
	"lib/db"
	"lib/log"
	"math"
	"strings"
)

func EsCreateNewDb(userLog string) error {
	body := strings.NewReader(`{
      "mappings": {
        "properties": {
          "Createtime": {
            "type": "date"
          }
        }
      }
    }`)

	res, err := db.GetElasticsearchClient().Indices.Create(userLog, db.GetElasticsearchClient().Indices.Create.WithBody(body))
	if err != nil {
		fmt.Println(io.EOF)
		log.Errorf("EsCreateData error: %v", err)
		return err
	}
	defer res.Body.Close()

	return nil
}

func EsCreateData(userLog string, myUserlog emodel.My_user_score_log) error {

	myUserlogJson, err := json.Marshal(myUserlog)
	if err != nil {
		log.Errorf("EsCreateData error: %v", err)
		return err
	}

	data := strings.NewReader(string(myUserlogJson))
	resp, err := db.GetElasticsearchClient().Index(userLog, data)
	if err != nil {
		fmt.Println(io.EOF)
		log.Errorf("EsCreateData error: %v", err)
	}
	resp.Body.Close()
	return err
}
func EsCreateUserLogData(myUserlog emodel.My_user_score_log) {

	myUserLogJson, err := json.Marshal(myUserlog)
	if err != nil {
		log.Errorf("EsCreateData error: %v", err)
		return
	}
	data := strings.NewReader(string(myUserLogJson))
	resp, err := db.GetElasticsearchClient().Index("user_score_logs", data)
	if err != nil {
		fmt.Println(io.EOF)
		log.Errorf("EsCreateData error: %v", err)
	}
	resp.Body.Close()

	return
}

func EsCreateUserLogDataAll(myUserlog []emodel.My_user_score_log) {

	var buf bytes.Buffer
	for _, i2 := range myUserlog {
		zyuanJson, _ := json.Marshal(i2)
		meta := []byte(`{"index":{"_index":"user_score_logs"}}` + "\n")
		data := []byte(string(zyuanJson) + "\n")
		buf.Grow(len(meta) + len(data))
		buf.Write(meta)
		buf.Write(data)

	}
	res, err := db.GetElasticsearchClient().Bulk(bytes.NewReader(buf.Bytes()))
	if err != nil {
		log.Errorf("Error performing bulk request: %s", err)
	}
	defer res.Body.Close()
	return
}

func EsCreateUserLevelsData(myUserLevels emodel.My_user_levels) {

	myUserLevelsgJson, err := json.Marshal(myUserLevels)
	if err != nil {
		log.Errorf("EsCreateData error: %v", err)
		return
	}
	data := strings.NewReader(string(myUserLevelsgJson))
	resp, err := db.GetElasticsearchClient().Index("user_levels", data)
	if err != nil {
		fmt.Println(io.EOF)
		log.Errorf("EsCreateData error: %v", err)
	}
	defer resp.Body.Close()

	return
}
func EsCreateUserLevelsDataAll(userLevels []emodel.My_user_levels) error {

	var buf bytes.Buffer
	for _, i2 := range userLevels {
		zyuanJson, _ := json.Marshal(i2)
		meta := []byte(`{"index":{"_index":"user_levels"}}` + "\n")
		data := []byte(string(zyuanJson) + "\n")
		buf.Grow(len(meta) + len(data))
		buf.Write(meta)
		buf.Write(data)

	}
	res, err := db.GetElasticsearchClient().Bulk(bytes.NewReader(buf.Bytes()))
	if err != nil {
		log.Errorf("Error performing bulk request: %s", err)
	}
	defer res.Body.Close()
	return nil
}

func EsUserLevelsSelect() error {
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"bool": map[string]interface{}{
				"must": []map[string]interface{}{
					{
						"term": map[string]interface{}{
							"Uid": 20253013, // 第一个字段及其值
						},
					},
					//{
					//	"term": map[string]interface{}{
					//		"Type": 1, // 第二个字段及其值
					//	},
					//},
				},
			},
		},
		"sort": []map[string]map[string]string{
			{"Levels": {"order": "desc"}}, // 根据 createtime 字段倒序排序
		},
	}
	queryJSon, _ := json.Marshal(query)
	repsss, err := db.GetElasticsearchClient().Search(
		db.GetElasticsearchClient().Search.WithIndex("user_levels"),
		db.GetElasticsearchClient().Search.WithBody(strings.NewReader(string(queryJSon))),
	)
	fmt.Println(repsss) //kqbCdZUBSLrAzhJIlRYe
	if err != nil {
		fmt.Println(io.EOF)
		log.Errorf("EsCreateData error: %v", err)
	}
	defer repsss.Body.Close()
	return err
}

func EsUserLevelsSelectOld() error {

	query := map[string]interface{}{
		//"query": map[string]interface{}{
		//	"bool": map[string]interface{}{
		//		"must": []map[string]interface{}{
		//			{
		//				"term": map[string]interface{}{
		//					"Uid": 20253013, // 第一个字段及其值
		//				},
		//			},
		//			{
		//				"term": map[string]interface{}{
		//					"Type": 1, // 第二个字段及其值
		//				},
		//			},
		//		},
		//	},
		//},
		"size": 0,
		"aggs": map[string]interface{}{
			"uid_levels": map[string]interface{}{ // 定义一个名为 uid_group 的聚合
				"terms": map[string]interface{}{ // 使用 terms 聚合来分组 Uid
					"field": "Uid", // 分组字段
					"size":  10,    // 返回的分组数量限制
					"order": map[string]string{
						"_count": "desc",
					},
				},
				"aggs": map[string]interface{}{ // 对每个 Uid 分组进行进一步聚合
					"levels_aggs": map[string]interface{}{ // 计算每个分组的文档数量
						"terms": map[string]interface{}{ // 使用 terms 聚合来分组 Uid
							"field": "Levels", // 分组字段
							"size":  10,       // 返回的分组数量限制
						},
					},
				},
			},
		},
		"sort": []map[string]map[string]string{
			{"Levels": {"order": "desc"}}, // 根据 createtime 字段倒序排序
		},
	}
	queryJSon, _ := json.Marshal(query)
	repsss, err := db.GetElasticsearchClient().Search(
		db.GetElasticsearchClient().Search.WithContext(context.Background()),
		db.GetElasticsearchClient().Search.WithIndex("user_levels"),
		db.GetElasticsearchClient().Search.WithBody(strings.NewReader(string(queryJSon))),
		db.GetElasticsearchClient().Search.WithTrackTotalHits(true),
	)
	fmt.Println(repsss) //kqbCdZUBSLrAzhJIlRYe
	if err != nil {
		fmt.Println(io.EOF)
		log.Errorf("EsCreateData error: %v", err)
	}
	defer repsss.Body.Close()
	return err
}

func EsUserLevelsUpdate() error {

	var buf strings.Builder
	buf.WriteString(`{
    "script": {
        "source": "ctx._source.IsNow = params.newIsNow; ctx._source.Levels = params.newLevels;",
        "lang": "painless",
        "params": {
            "newIsNow": 1,
            "newLevels": 40
        }
    },
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "Uid": 20253013
                    }
                },
                {
                    "match": {
                        "Levels": 14
                    }
                }
            ]
        }
    }
}`)

	// 发送 UpdateByQuery 请求
	req := esapi.UpdateByQueryRequest{
		Index:     []string{"user_levels"},         // 替换为你的索引名
		Body:      strings.NewReader(buf.String()), // 使用上面构建的 JSON 字符串作为请求体
		Conflicts: "proceed",                       // 处理冲突的方式，例如 "proceed" 或 "abort"
	}

	repsss, err := req.Do(context.Background(), db.GetElasticsearchClient()) // 使用 context 控制请求的生命周期
	if err != nil {
		log.Errorf("Error getting response: %s", err)
	}
	defer repsss.Body.Close()
	return nil
}

func EsUserLogsHistorySelect(typess int, userId uint64, page, index int) (*dto.PaginationList[emodel.My_user_score_log], error) {
	var mmmm float64
	//start := 0
	pageSize := 15
	from := (page - 1) * pageSize
	var query any
	if typess == 999993 || typess == 999994 {
		typesssss := 3
		flag := 50
		if typess == 999994 {
			flag = 3
		}

		query = map[string]interface{}{
			"query": map[string]interface{}{
				"bool": map[string]interface{}{
					"must": []map[string]interface{}{
						{
							"term": map[string]interface{}{
								"UserId": userId, // 第一个字段及其值
							},
						},
						{
							"term": map[string]interface{}{
								"Type": typesssss, // 第二个字段及其值
							},
						}, {
							"term": map[string]interface{}{
								"Flag": flag, // 第二个字段及其值
							},
						},
					},
				},
			},
			"from": from,
			"size": pageSize,
			"sort": []map[string]map[string]string{
				{"Createtime": {"order": "desc"}}, // 根据 createtime 字段倒序排序
			},
		}
	} else {
		if (typess == 11 || typess == 3) && index > 0 {

			typessaa := []int{
				typess,
			}

			flag := []int{ // 【直推-间推-喂养】
				6, 7,
			}
			if typess == 11 {

				typessaa = []int{
					11, 12,
				}
				if index == 2 { //  每日任务，循环任务
					flag = []int{
						3, 4, 2,
					}
				} else if index == 3 { //～大逃杀，抢地主，获得的饲料
					flag = []int{
						1, 5, 8, 9, 10,
					}
				} else if index == 4 {
					flag = []int{
						12,
					}

					mmmstr := fmt.Sprintf(`{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "UserId": %d
          }
        },
        {
          "terms": {
            "Type": [11, 12]
          }
        },
        {
          "terms": {
            "Flag": [12]
          }
        }
      ]
    }
  },
  "aggs": {
    "total_score": {
      "sum": {
        "script": {
          "source": "params._source.Score"
        }
      }
    }
  }
}`, userId)

					req11 := esapi.SearchRequest{
						Index: []string{"user_score_logs"}, // 索引名
						Body:  strings.NewReader(mmmstr),
					}

					resss, errs := req11.Do(context.Background(), db.GetElasticsearchClient())
					if errs == nil {
						defer resss.Body.Close()

						newDatasss := resss.String()[9:]

						var responsess newSumScore
						fmt.Println(newDatasss)
						errs = json.Unmarshal([]byte(newDatasss), &responsess)
						if errs == nil {
							mmmm = responsess.Aggregations.TotalScore.Value
						}
					}

				} else if index == 5 {
					flag = []int{
						11, 0,
					}
				}

			} else if typess == 3 {
				//	//flag 0兑换 1转赠获得 2消费积分 3提取 4提取驳回 10系统操作 36游戏的奖励 37通天塔奖励 38抽奖1 39抽奖10
				//	//50转赠 51养鱼分红 52直推捞鱼 53间推捞鱼 54参加游戏2 55游戏2的奖励 56后台取消转赠
				flag = []int{ // 星族馆，，，，，
					51,
				}
				if index == 1 { //  抢地主
					flag = []int{
						51,
					}
				} else if index == 2 { //  抢地主
					flag = []int{
						54, 55, 36, 10,
					}
				} else if index == 3 { //星仙侠
					flag = []int{
						37, 40, 39, 999999,
					}
				} else if index == 4 { //捕捞
					flag = []int{
						52, 53, 38,
					}
				} else if index == 5 { //传送
					flag = []int{
						50, 56,
					}
				} else if index == 6 { //解锁
					flag = []int{
						1, 2,
					}
				} else if index == 7 { //解锁
					flag = []int{
						57, 58, 59,
					}
				} else { //解锁
					flag = []int{
						0,
					}
				}
			}

			query = map[string]interface{}{
				"query": map[string]interface{}{
					"bool": map[string]interface{}{
						"must": []map[string]interface{}{
							{
								"term": map[string]interface{}{
									"UserId": userId, // 第一个字段及其值
								},
							},
							{
								"terms": map[string]interface{}{
									"Type": typessaa, // 第二个字段及其值
								},
							},
							{
								"terms": map[string]interface{}{
									"Flag": flag, // 第二个字段及其值
								},
							},
						},
					},
				},
				"from": from,
				"size": pageSize,
				"sort": []map[string]map[string]string{
					{"Createtime": {"order": "desc"}}, // 根据 createtime 字段倒序排序
				},
			}

		} else {
			query = map[string]interface{}{
				"query": map[string]interface{}{
					"bool": map[string]interface{}{
						"must": []map[string]interface{}{
							{
								"term": map[string]interface{}{
									"UserId": userId, // 第一个字段及其值
								},
							},
							{
								"term": map[string]interface{}{
									"Type": typess, // 第二个字段及其值
								},
							},
						},
					},
				},
				"from": from,
				"size": pageSize,
				"sort": []map[string]map[string]string{
					{"Createtime": {"order": "desc"}}, // 根据 createtime 字段倒序排序
				},
			}
		}

	}

	queryJSON, err := json.Marshal(query)
	if err != nil {
		log.Fatalf("Error marshalling query: %s", err)
	}

	req := esapi.SearchRequest{
		Index: []string{"user_score_logs"}, // 索引名
		Body:  strings.NewReader(string(queryJSON)),
	}

	res, err := req.Do(context.Background(), db.GetElasticsearchClient())
	if err != nil {
		log.Fatalf("Error executing the search request: %s", err)
	}
	defer res.Body.Close()

	newData := res.String()[9:]

	var response emodel.EsScoreSelect
	err = json.Unmarshal([]byte(newData), &response)

	if err != nil {
		return nil, err
	}
	if response.Hits.Total.Value == 0 {
		//没有数据
	} else {

	}
	total := response.Hits.Total.Value
	var newDataList dto.PaginationList[emodel.My_user_score_log]
	newDataList.Total = int64(total)
	newDataList.Page = page
	newDataList.PageSize = pageSize
	for _, hit := range response.Hits.Hits {
		num := decimal.NewFromFloat(hit.Source.Score)
		rounded := num.Round(4)              // 保留 4 位小数
		roundedFloat, _ := rounded.Float64() // 转换为 float
		// 输出: float64
		hit.Source.Score = roundedFloat
		newDataList.Items = append(newDataList.Items, hit.Source)
	}

	newDataList.Mmm = mmmm
	return &newDataList, nil
}

type newSumScore struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore interface{}   `json:"max_score"`
		Hits     []interface{} `json:"hits"`
	} `json:"hits"`
	Aggregations struct {
		TotalScore struct {
			Value float64 `json:"value"`
		} `json:"total_score"`
	} `json:"aggregations"`
}

type sumGameLog struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore interface{}   `json:"max_score"`
		Hits     []interface{} `json:"hits"`
	} `json:"hits"`
	Aggregations struct {
		GroupByUser struct {
			DocCountErrorUpperBound int `json:"doc_count_error_upper_bound"`
			SumOtherDocCount        int `json:"sum_other_doc_count"`
			Buckets                 []struct {
				Key      int `json:"key"`
				DocCount int `json:"doc_count"`
				SumScore struct {
					Value float64 `json:"value"`
				} `json:"sum_score"`
			} `json:"buckets"`
		} `json:"group_by_user"`
		TotalScoreSum struct {
			Value float64 `json:"value"`
		} `json:"total_score_sum"`
		UserScoreSum struct {
			Value float64 `json:"value"`
		} `json:"user_score_sum"`
	} `json:"aggregations"`
}

type RankSSS struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore interface{}   `json:"max_score"`
		Hits     []interface{} `json:"hits"`
	} `json:"hits"`
	Aggregations struct {
		GroupByUser struct {
			DocCountErrorUpperBound int `json:"doc_count_error_upper_bound"`
			SumOtherDocCount        int `json:"sum_other_doc_count"`
			Buckets                 []struct {
				Key      int `json:"key"`
				DocCount int `json:"doc_count"`
				SumScore struct {
					Value float64 `json:"value"`
				} `json:"sum_score"`
			} `json:"buckets"`
		} `json:"group_by_user"`
		TotalScoreSum struct {
			Value float64 `json:"value"`
		} `json:"total_score_sum"`
		UserScoreSum struct {
			Value float64 `json:"value"`
		} `json:"user_score_sum"`
	} `json:"aggregations"`
}

func EsUserLogsHistorySelectTzSum(userId uint64, page int) (float64, error) {

	query := map[string]interface{}{
		"size": 0, // 不返回原始文档，只返回聚合结果
		"query": map[string]interface{}{
			"bool": map[string]interface{}{
				"must": []interface{}{
					map[string]interface{}{"term": map[string]interface{}{"Type": 0}},
					map[string]interface{}{"term": map[string]interface{}{"Memo.keyword": "参与游戏获得"}},
					map[string]interface{}{"term": map[string]interface{}{"UserId": userId}}, // 新增 UserId=11 条件

				},
			},
		},
		"aggs": map[string]interface{}{
			"user_score_sum": map[string]interface{}{ // 专门查询 UserId=11 的分数总和
				"sum": map[string]interface{}{
					"field": "Score",
				},
			},
			// 保留原来的分组聚合（如果需要）
			"group_by_user": map[string]interface{}{
				"terms": map[string]interface{}{
					"field": "UserId",
					"size":  10000,
					"order": map[string]interface{}{
						"sum_score": "asc",
					},
				},
				"aggs": map[string]interface{}{
					"sum_score": map[string]interface{}{
						"sum": map[string]interface{}{"field": "Score"},
					},
				},
			},
			"total_score_sum": map[string]interface{}{
				"sum": map[string]interface{}{"field": "Score"},
			},
		},
	}

	// Convert query to JSON
	queryJSON, err := json.Marshal(query)
	if err != nil {
		log.Fatalf("Error marshaling query: %s", err)
	}

	req := esapi.SearchRequest{
		Index: []string{"user_score_logs"}, // 索引名
		Body:  strings.NewReader(string(queryJSON)),
	}

	res, err := req.Do(context.Background(), db.GetElasticsearchClient())
	if err != nil {
		log.Fatalf("Error executing the search request: %s", err)
	}
	defer res.Body.Close()

	newData := res.String()[9:]

	var response RankSSS
	err = json.Unmarshal([]byte(newData), &response)

	if err != nil {
		return 0, err
	}

	return response.Aggregations.UserScoreSum.Value, nil
}

func EsUserLogsHistorySelectTzRank(opid uint64, start, end string) (any, error) {

	query := map[string]interface{}{
		"size": 0, // 不返回原始文档，只返回聚合结果
		"query": map[string]interface{}{
			"bool": map[string]interface{}{
				"must": []interface{}{
					map[string]interface{}{"term": map[string]interface{}{"Type": 0}},
					map[string]interface{}{"term": map[string]interface{}{"Memo.keyword": "参加游戏"}},
					map[string]interface{}{
						"range": map[string]interface{}{
							"Createtime": map[string]interface{}{
								"gte": start,
								"lte": end,
							},
						},
					},
				},
			},
		},
		"aggs": map[string]interface{}{
			"user_score_sum": map[string]interface{}{ // 专门查询 UserId=11 的分数总和
				"sum": map[string]interface{}{
					"field": "Score",
				},
			},
			// 保留原来的分组聚合（如果需要）
			"group_by_user": map[string]interface{}{
				"terms": map[string]interface{}{
					"field": "UserId",
					"size":  1000,
					"order": map[string]interface{}{
						"sum_score": "asc",
					},
				},
				"aggs": map[string]interface{}{
					"sum_score": map[string]interface{}{
						"sum": map[string]interface{}{"field": "Score"},
					},
				},
			},
			"total_score_sum": map[string]interface{}{
				"sum": map[string]interface{}{"field": "Score"},
			},
		},
	}

	// Convert query to JSON
	queryJSON, err := json.Marshal(query)
	if err != nil {
		log.Fatalf("Error marshaling query: %s", err)
	}

	req := esapi.SearchRequest{
		Index: []string{"user_score_logs"}, // 索引名
		Body:  strings.NewReader(string(queryJSON)),
	}

	res, err := req.Do(context.Background(), db.GetElasticsearchClient())
	if err != nil {
		log.Fatalf("Error executing the search request: %s", err)
	}
	defer res.Body.Close()

	newData := res.String()[9:]

	var response sumGameLog
	err = json.Unmarshal([]byte(newData), &response)

	if err != nil {
		return 0, err
	}
	var sss []map[string]interface{}

	i := 1
	dj := 999
	for _, bucket := range response.Aggregations.GroupByUser.Buckets {
		id := bucket.Key
		idStr := fmt.Sprintf("%d", id)
		i++

		if i < 52 {
			sss = append(sss, map[string]interface{}{
				"ID":    idStr[:5] + "***",
				"Score": math.Abs(bucket.SumScore.Value),
				"dj":    dj,
			})
		}
		if uint64(id) == opid {
			sss[0]["dj"] = i - 1
		}

	}

	return sss, nil
}

func roundToFourDecimalPlaces(num float64) float64 {
	return math.Round(num*10000) / 10000
}

func EsUserLogsSelect() error {

	query := map[string]interface{}{
		//"query": map[string]interface{}{
		//
		//	"bool": map[string]interface{}{
		//		"must": []map[string]interface{}{
		//			{
		//				"term": map[string]interface{}{
		//					"UserId": 20265398, // 第一个字段及其值
		//				},
		//			},
		//			//{
		//			//	"term": map[string]interface{}{
		//			//		"Type": 1, // 第二个字段及其值
		//			//	},
		//			//},
		//		},
		//	},
		//},
		"sort": []map[string]map[string]string{
			{"Createtime": {"order": "desc"}}, // 根据 createtime 字段倒序排序
		},
	}

	queryJSon, _ := json.Marshal(query)
	repsss, err := db.GetElasticsearchClient().Search(
		db.GetElasticsearchClient().Search.WithIndex("user_score_logs"),
		db.GetElasticsearchClient().Search.WithBody(strings.NewReader(string(queryJSon))),
		db.GetElasticsearchClient().Search.WithTrackTotalHits(true),
	)
	fmt.Println(repsss)
	if err != nil {
		fmt.Println(io.EOF)
		log.Errorf("EsCreateData error: %v", err)
	}
	defer repsss.Body.Close()
	return err
}

func EsGetGameXhNum() (string, error) {

	query := map[string]interface{}{
		"query": map[string]interface{}{
			"term": map[string]interface{}{
				"Flag": 43, // 第二个字段及其值
			},
		},
		"aggs": map[string]interface{}{
			"total_money": map[string]interface{}{
				"sum": map[string]interface{}{
					"field": "Score", // 第二个字段及其值
				},
			},
		},
		"size": 0,
	}
	queryJSon, _ := json.Marshal(query)
	// 发送 UpdateByQuery 请求
	repsss, err := db.GetElasticsearchClient().Search(
		db.GetElasticsearchClient().Search.WithIndex("user_score_logs"),
		db.GetElasticsearchClient().Search.WithBody(strings.NewReader(string(queryJSon))),
		db.GetElasticsearchClient().Search.WithTrackTotalHits(true),
	)
	if err != nil {
		return "", err
	}
	body, err := ioutil.ReadAll(repsss.Body)
	if err != nil {
		return "", fmt.Errorf("error reading response body: %w", err)
	}

	var respEsXh RespEsXh
	if err = json.Unmarshal(body, &respEsXh); err != nil {
		return "", err
	}

	newValue := 0 - respEsXh.Aggregations.TotalMoney.Value
	defer repsss.Body.Close()
	fmt.Println(newValue)
	return fmt.Sprintf("%.2f", newValue), nil
}

type RespEsXh struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore interface{}   `json:"max_score"`
		Hits     []interface{} `json:"hits"`
	} `json:"hits"`
	Aggregations struct {
		TotalMoney struct {
			Value float64 `json:"value"`
		} `json:"total_money"`
	} `json:"aggregations"`
}
